package net.adetech.cjg.outerservice.utils;

import com.alibaba.fastjson.JSONObject;
import com.sccba.open.HttpClient;
import net.adetech.framework.utils.SerializeUtil;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class BankUtil {


    private String signKey = "152861AAD5DEAF43CD157D321ACE8F";

    private String certFilePath = "/Users/zhangsong/cjg_cert/";
    private String url = "https://60.208.131.91:12816";
    private String bankId = "816";
    private String bizKey = "TPM1001";

    private String clientId = "ZAATPM00";
    private String clientSecret = "ZAATPM00";
    private String actionAndTransId = "ZAATPM00/TPM1001";

    private static Map<String, String> signFieldListMap = new HashMap<>();

    static {
        signFieldListMap.put("801101_reqSignatureSeq", "yybs|cpdm|jydm|sys_seqno|order_id|voucher_id|order_life|amt_source|amount|amt_currency|trans_datetime|mchnt_cd|sub_mchnt_cd|device_mac|operator_id");

    }


    public JSONObject call(JSONObject params) {
        String sign = getDataSign(params);
        params.put("sign", sign);
        String data = params.toJSONString();

        //data = "abcd";

        System.out.println("\ndata字段明文:");
        System.out.println(data);


        data = SerializeUtil.encodeBase64(data);
        System.out.println("\ndata base64加密后:");
        System.out.println(data);


        String accessToken = this.getAccessToken();
        String nonceStr = UUID.randomUUID().toString();
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmssSSSS").format(new Date());
        JSONObject requestJson = new JSONObject();
        requestJson.put("data",data);
        requestJson.put("access_token",accessToken);
        requestJson.put("nonce_str",nonceStr);
        requestJson.put("bkId",bankId);
        requestJson.put("timeStamp",timeStamp);
        requestJson.put("bizKey",bizKey);
        requestJson.put("trans_source","01"); //回调地址


        String requestJsonString = requestJson.toJSONString();
        System.out.println("\n请求Json:");
        System.out.println(requestJsonString);

        JSONObject resultJson = null;
        try {
            System.out.println("\n调用sendMsg返回:");
            resultJson = JSONObject.parseObject(HttpClient.sendMsg(actionAndTransId,requestJsonString));
            String returnData = SerializeUtil.decodeBase64(resultJson.getString("data"));
            System.out.println("\n return data:");
            System.out.println(returnData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultJson;
    }


    /**
     * 获取AccessToken
     *
     * @return accessToken
     */
    public String getAccessToken() {
        HttpClient.initFilePath(certFilePath, url, 10000, 10000, bankId);
        String accessToken = null;
        try {
            System.out.println("\n调用 获取token返回:");
            //获取token
            JSONObject tokenJson = JSONObject.parseObject(HttpClient.token("client_id="+clientId+"&client_secret="+clientSecret+"&grant_type=client_credentials"));
            accessToken = tokenJson.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }


    /**
     * 获取加签字符串
     *
     * @param params 请求参数
     * @return 加签字符串
     */
    private String getDataSign(JSONObject params) {
        String jydm = params.getString("jydm");
        String signFieldList[] = signFieldListMap.get(jydm + "_reqSignatureSeq").split("\\|");
        String signParams = "";
        for (String fieldName : signFieldList) {
            String fieldValue = params.getString(fieldName);
            if (fieldValue != null && !fieldValue.equals("")) {
                if (!signParams.equals("")) {
                    signParams += "&";
                }
                signParams += fieldName + "=" + fieldValue;
            }
        }

        signParams += "&sign_key=" + signKey;

        System.out.println("\n加签前字符串:");
        System.out.println(signParams);
        String sign = MD5(signParams).toUpperCase();

        System.out.println("\n加签值:");
        System.out.println(sign);
        return sign;
    }

    public static String MD5(String key) {
        char hexDigits[] = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
        };
        try {
            byte[] btInput = key.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    public JSONObject getQrcode(String seqno,String orderId,String title,String amount)
    {
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        JSONObject requestJson = new JSONObject();
        requestJson.put("yybs","026");  //应用代码 固定填写026
        requestJson.put("cpdm","9990002601");  //产品代码  固定填写9990002601
        requestJson.put("jydm","801101");    //交易处理代码  填写801101
        requestJson.put("sys_seqno",seqno); //请求流水号
        requestJson.put("order_id",orderId);  //商户订单号
        requestJson.put("order_title",title); //订单标题
        requestJson.put("order_description",title); //订单标题

        requestJson.put("order_life","60");  //订单有效期 单位为分钟
        requestJson.put("amt_source","00"); //交易金额来源 固定填写为00-订单上送
        requestJson.put("amount",amount);  //交易金额
        requestJson.put("amt_currency","CNY"); //交易币种  CNY 人民币
        requestJson.put("trans_datetime",timeStamp);  //交易时间 YYYYMMDDhhmmss
        requestJson.put("mchnt_cd","816370650940001");  //商户号
        requestJson.put("mchnt_mcc","115094"); //商户类型
        requestJson.put("notify_url","http://adetech.s1.natapp.cc/cjg/payResult"); //回调地址
        requestJson.put("trans_source","01"); //回调地址


        JSONObject resultJson = this.call(requestJson);
        String dataString = resultJson.getString("data");
        dataString = SerializeUtil.decodeBase64(dataString);
        JSONObject dataJson = JSONObject.parseObject(dataString);
        return dataJson;
    }

}
